package com.lry.future.demo2;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author JiangJie
 * @create 2020-11-23 13:56
 */
public class Executors {


    public static void main(String[] args) {
        Future<String> future = submit(()->{
            return "hello";
        });
        //2s空轮询，性能太差
        System.out.println(future.get());
    }

    public static <T> Future<T> submit(Callable<T> callable){

        AtomicReference<T> result = new AtomicReference<T>();
        AtomicBoolean flag = new AtomicBoolean(false);

        Future<T> future = new Future<T>() {
            //阻塞方法
            @Override
            public T get() {
                while(!isDone()){}
                return result.get();
            }

            @Override
            public boolean isDone() {
                return flag.get();
            }
        };

        //模拟执行任务耗时
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                T t = callable.run();
                flag.set(true);
                result.set(t);
            }
        }).start();

        //future会异步返回，不会等任务执行完

        return future;
    }
}
